<template>
    <view class="main">
        <!-- 遮罩 -->
        <scroll-view class="mask" v-if="isShow" @click="closeMask">
            <canvas canvas-id="posterCanvas" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 10;"></canvas>
            <image class="mask-poster" :src="posterUrl" v-if="showOriginalImages"></image>
            <image class="mask-invit-QR" :src="user.qrCode" v-if="showOriginalImages"></image>
            <view class="mask-button-box">
                <view class="share-button" @click="sharePoster">分享海报</view>
            </view>
        </scroll-view>

        <!-- 空白页 -->
        <view class="w100 flex-column align-center padding-column20 fixed-auto" v-if="backGround">
            <image src="https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/assets/empty.png"
                style="width: 256rpx; height: 256rpx;"></image>
            <text style="color: #81868e;">暂无邀请信息</text>
        </view>
        <!-- 卡片 -->
        <view class="top-card">
            <view class="invite-number-text">已邀请的用户数</view>
            <view class="invite-number">{{ inviteNumber }}</view>
            <!-- 二维码 -->
            <image class="invite-QR" :src="user.qrCode" @click="clickQR"></image>
        </view>
		
		
        <!-- 搜索框 -->
        <view class="w100 flex-between align-center padding-row30">
            <!-- 下拉选择器 -->
            <view class="select-type" @click="show=true">{{ typeList[selectIndex].text }}</view>
			
            <!-- 搜索图标 -->
			<view class="query-input flex align-center flex-1 padding-row20">
				<u-icon name="search" color="#887D75" size="32"></u-icon>
				<input typy="number" placeholder="输入手机号" @input="queryInvite" style="padding-left: 15rpx;"/>
			</view>
            
        </view>
        <!-- 用户列表 -->
        <view class="user-card" v-for="(item, index) in userList" :key="index">
			<view class="flex-between">
				<view class="user-register-time">注册时间：{{ item.createTime }}</view>
				<view class="user-type">{{ item.membershipName || "" }}</view>
			</view>
            <view class="Divider"></view>
            <view class="w100 user-info flex-between align-center">
				<view class="flex align-center">
					<!-- <image class="user-icon" src="https://aiet-file-center.oss-cn-hangzhou.aliyuncs.com/shuziren/image/user3228561.png"></image> -->
					<u-icon name="account" size="36" color="#FFA0A0"></u-icon>
					<view class="user-phone">{{ item.phone }}</view>
				</view>
                <view class="user-phone-button" :data-phone-number="item.phone" @click="makePhoneCall">拨打电话</view>
            </view>
        </view>
        <view class="no-more" v-if="noMore">没有更多数据了</view>
		
		<u-action-sheet :list="typeList" v-model="show" @click="handleClick" ></u-action-sheet>
    </view>
</template>
<script>
import { mapState } from "vuex"
export default {
    // 数据
    data() {
        return {
			// 控制隐藏绘制前的海报
            showOriginalImages: true,
            // 判断海报是否绘制完成
            isPosterDrawn: false,
            // 判断是否在绘制
            isDrawing: false,
			
			posterUrl: "https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/poster.jpg",
            // 邀请人数
            inviteNumber: 0,
            // 遮罩
            isShow: false,
            // 查询
            selectIndex: 0,
            // 二维码
            QR: "",
            typeList: [
                {
                    text: "全部",
                    value: null,
                },
                {
                    text: "基础视频会员",
                    value: 1,
                },
                {
                    text: "银牌采购商",
                    value: 2,
                },
                {
                    text: "金牌采购商",
                    value: 3,
                },
                {
                    text: "钻石采购商",
                    value: 4,
                }
            ],
            // 查询条件
            searchForm: {
                phone: "",
                membershipId: null,
                page: 0,
                size: 10
            },
            // 分页参数
            page: {
                // 总页数
                totalPages: 0,
                // 总条数
                size: 10,
                // 当前页
                current: 1
            },
            // 用户列表
            userList: [],
            // 空白背景判断
            backGround: false,
            // 没有更多数据的判断
            noMore: false,
            // 加载
            loading: false,
			show: false,
			
			// 临时海报路径
			tempPosterPath: ''

        };
    },
    computed: {
        ...mapState({
            user: state => state.user
        })
    },

    // 生命周期
    onLoad() {
        this.getUserList(this.searchForm);
        this.getQR();
		wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },

    methods: {
        // 获取数据
        async getUserList(searchForm) {
            // 打印当前查询数据
            console.log('当前查询数据', this.searchForm);
            const res = await this.$request("/aiet-user-center/user/getSubUserList", searchForm, "POST", "application/json");
            if (res.code === 200) {
                // 邀请人数
                this.inviteNumber = res.data.content.length;
                // 邀请列表
                this.userList = res.data.content;
                console.log("用户列表res.data", res.data);
                console.log("用户列表this.userList", this.userList);
                // 控制背景和底部提示显示
                if (this.userList.length > 0) {
                    this.backGround = false;
                    this.noMore = true;
                }else{
                    this.backGround = true;
                    this.noMore = false;
                }
                // 更新总页数
                this.page.totalPages = res.data.page.totalPages;
            }
        },
        
		// 获取QR码
        async getQR(userId) {
            const res = await this.$request("/aiet-user-center/user/getQRCode", { userId: userId }, "GET");
            if (res.code === 200) {
                this.QR = res.data;
                // 打印
                console.log("获取小程序码", res.data.data);
            }
        },
        // 下拉框查询
        handleClick: function (e) {
			console.log(e)
			this.selectIndex = e
            this.searchForm.membershipId = e== 0 ? null : e
            this.getUserList(this.searchForm)
        },
		
        // 输入框查询
        queryInvite: function (e) {
            console.log("输入框输入内容：" + e.detail.value);
            this.searchForm.phone = e.detail.value
            this.getUserList(this.searchForm)
        },
		
        // 拨打电话
        makePhoneCall: function (event) {
            const phoneNumber = event.currentTarget.dataset.phoneNumber;
            wx.makePhoneCall({
                phoneNumber: phoneNumber,
                success: function () {
                    console.log("拨打电话成功");
                },
                fail: function (err) {
                    console.error("拨打电话失败", err);
                },
            });
        },
        // 加载更多数据
        async loadMore() {
            if (this.loading || this.searchForm.page >= this.page.totalPages) {
                return;
            }
            this.loading = true;
            this.searchForm.page += 1;
            await this.getUserList(this.searchForm);
        },
        // 监听滚动事件
        onScroll(event) {
            const { scrollTop, scrollHeight, clientHeight } = event.target;
            if (scrollTop + clientHeight >= scrollHeight - 10) {
                this.loadMore();
            }
        },
        // 点击二维码打开遮罩层
        clickQR() {
            this.isShow = true;
			this.drawPoster();
        },
        // 关闭遮罩层
        closeMask() {
            this.isShow = false;
        },
		
		 // 绘制海报
        drawPoster() {
            if (this.isDrawing) {
                console.log("正在绘制中，请稍后再试");
                return;
            }
            this.isDrawing = true; // 设置正在绘制标志
            const ctx = wx.createCanvasContext('posterCanvas');
            const screenWidth = wx.getSystemInfoSync().windowWidth;
            const screenHeight = wx.getSystemInfoSync().windowHeight;
            // const posterWidth = screenWidth; // 调整为全屏宽度
            // const posterHeight = screenHeight; // 调整为全屏高度
            const posterWidth = screenWidth * 0.75;
            const posterHeight = posterWidth * (1920 / 1080); // 调整为竖屏比例
            const qrCodeSize = posterWidth * 0.6;

            // 计算海报在 canvas 中的位置，使其上下左右居中
            // const posterX = 0; // 调整为全屏宽度 
            // const posterY = 0; // 调整为全屏高度
            const posterX = (screenWidth - posterWidth) / 2;
            const posterY = (screenHeight - posterHeight) / 2 - 30;

            // 计算二维码的位置，使其在海报正中间
            const qrCodeX = posterX + (posterWidth - qrCodeSize) / 2;
            const qrCodeY = posterY + (posterHeight - qrCodeSize) / 2 - 90;

            // 绘制海报
            wx.getImageInfo({
                src: this.posterUrl,
                success: (res) => {
                    ctx.drawImage(res.path, posterX, posterY, posterWidth, posterHeight);

                    // 绘制二维码
                    wx.getImageInfo({
                        src: this.user.qrCode,
                        success: (qrRes) => {
                            ctx.drawImage(qrRes.path, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
                            ctx.draw(false, () => {
                                console.log("海报绘制完成");
                                this.isPosterDrawn = true; // 设置海报绘制完成标志
                                this.isDrawing = false; // 重置正在绘制标志
                                this.showOriginalImages = false; // 隐藏原本的 <image> 元素
                            });
                        }
                    });
                }
            });
        },
		 // 隐藏原本的 <image> 元素
        hideOriginalImages() {
            const posterImage = document.querySelector('.mask-poster');
            const qrCodeImage = document.querySelector('.mask-invit-QR');
            if (posterImage) posterImage.style.display = 'none';
            if (qrCodeImage) qrCodeImage.style.display = 'none';
        },
		
        // 保存海报到手机
        savePoster() {
            if (!this.isPosterDrawn) {
                console.log("海报尚未绘制完成，无法保存");
                return;
            }
            wx.canvasToTempFilePath({
                canvasId: 'posterCanvas',
                success: (res) => {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: () => {
                            wx.showToast({
                                title: '保存成功',
                                icon: 'success',
                                duration: 2000
                            });
                        },
                        fail: (err) => {
                            console.error("保存失败", err);
                        }
                    });
                },
                fail: (err) => {
                    console.error("导出图片失败", err);
                }
            });
        },
        // 分享海报到微信好友列表
        sharePoster() {
            if (!this.isPosterDrawn) {
                console.log("海报尚未绘制完成，无法分享");
                return;
            }
            wx.canvasToTempFilePath({
                canvasId: 'posterCanvas',
                success: (res) => {

                    console.log("分享海报绘制完成:", res.tempFilePath);

                    wx.showShareImageMenu({
                        path: res.tempFilePath
                    })

                },
                fail: (err) => {
                    console.error("导出图片失败", err);
                }
            });
        },
        // 定义分享内容
        onShareAppMessage() {
            if (this.tempPosterPath) {
                return {
                    title: '分享海报',
                    imageUrl: this.tempPosterPath,
                    path: '/pages/mine/invite' // 分享的路径
                };
            }
        }

    },
};
</script>
<style>
.main {
    width: 100%;
    height: 100vh;
    /* background-color: #f5f5f5; */
    padding-top: 1rpx;
}

/* 邀请卡片 */
.top-card {
    width: 90%;
    height: 20%;
    background: #FFD1D1;
    border-radius: 15rpx;
    margin: 30rpx auto 0 auto;
    padding: 1rpx;
    margin-bottom: 30rpx;
}

/* 邀请人数文本 */
.invite-number-text {
    padding-top: 1rpx;
    display: inline-block-block;
    margin-top: 40rpx;
    font-size: 35rpx;
    color: white;
    margin-left: 30rpx;
}

/* 邀请人数 */
.invite-number {
    display: flex;
    color: white;
    font-size: 80rpx;
    margin-top: 20rpx;
    margin-left: 55rpx;
}

.user-info {
	padding: 20rpx 40rpx;
}

/* 二维码 */
.invite-QR {
    position: absolute;
    width: 150rpx;
    height: 150rpx;
    margin-top: -137rpx;
    margin-left: 60%;
    border-radius: 20rpx;
}


/* 筛选框 */
.select-type {
    z-index: 2;
    width: 200rpx;
    height: 60rpx;
	text-align: center;
    background-color: white;
    border-radius: 15rpx;
    font-size: 25rpx;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(178, 178, 178, 0.25),
        inset 0rpx 8rpx 8rpx 0rpx rgba(255, 255, 255, 0.25);
    line-height: 60rpx;
}

/* 选择内容 */
.picker-content {
    width: 100%;
    text-align: center;
    font-size: 25rpx;
}



/* 搜索框 */
.query-input {
	width: 100%;
    height: 60rpx;
	margin-left: 30rpx;
    border-radius: 15rpx;
    background-color: white;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(178, 178, 178, 0.25), inset 0rpx 8rpx 8rpx 0rpx rgba(255, 255, 255, 0.25);
}

/* 用户卡片 */
.user-card {
    width: 90%;
    /* height: 12%; */
    background-color: white;
    border-radius: 15rpx;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(178, 178, 178, 0.25), inset 0rpx 8rpx 8rpx 0rpx rgba(255, 255, 255, 0.25);
    margin: 20rpx auto 0 auto;
    padding: 1rpx;
}

/* 用户注册时间 */
.user-register-time {
    padding: 20rpx 40rpx;
}

/* 用户类型 */
.user-type {
    display: inline-block;
    margin-top: 20rpx;
    margin-left: 100rpx;
}

/* 分割线 */
.Divider {
    width: 90%;
    height: 1rpx;
    /* background-color: black; */
	margin: 0 auto;
    border: 1rpx dashed lightgray;
}

/* 用户手机号 */
.user-phone {
    color: #333;
	padding-left: 15rpx;
	font-weight: 600;
}

/* 按钮伪元素 */
.user-phone-button::after {
    border: 0;
}

/* 拨打电话按钮 */
.user-phone-button {
    width: 140rpx;
    height: 60rpx;
	line-height: 58rpx;
	text-align: center;
    font-size: 24rpx;
    color: #FA6464;
    background-color: white;
    border-radius: 12rpx;
    border: 1rpx solid #FA6464;
}

/* 拨打电话按钮中文本 */
.button-text {
    font-size: 24rpx;
    color: rgb(248, 195, 41);
    display: inline-block;
    margin-top: -7rpx;
}

/* 遮罩层 */
.mask {
    position: fixed;
    display: flex;
    z-index: 9;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    justify-content: center;
    align-items: center;
}

/* 遮罩层二维码 */
.mask-invit-QR {
    position: absolute;
    width: 0rpx;
    height: 0rpx;
    /* background-color: white; */
    /* 居中 */
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 9;
}

/* 遮罩层海报 */
.mask-poster {
    width: 0;
    height: 0;
    background-color: white;
    /* 居中 */
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20rpx auto;
}

/* 保存和分享海报按钮 */
.mask-button-box {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    z-index: 10;
    bottom: 20rpx;
    width: 100%;
    margin-bottom: 100rpx;
}

/* 保存按钮 */
.save-button {
    align-items: center;
    display: flex;
    justify-content: center;
    width: 200rpx;
    height: 60rpx;
    background-color: #007aff;
    color: white;
    border-radius: 10rpx;
}

/* 分享按钮 */
.share-button {
    align-items: center;
    display: flex;
    justify-content: center;
    width: 300rpx;
    height: 80rpx;
    background-color: #FFA0A0;
    color: white;
    border-radius: 10rpx;
}


/* 无更多数据 */
.no-more {
    width: 200rpx;
    height: 100rpx;
    display: flex;
    margin: 40rpx auto;
}
</style>
